// 商品列表相关变量
let currentPage = 0;
let isLoading = false;
let hasMore = true;
let currentKeyword = '';
let searchHistory = [];

// 加载商品列表
async function loadProducts(reset = false) {
    if (isLoading || (!hasMore && !reset)) return;

    if (reset) {
        currentPage = 0;
        hasMore = true;
        document.querySelector('.products-grid').innerHTML = '';
    }

    isLoading = true;
    const loadMoreButton = document.querySelector('.load-more');
    if (loadMoreButton) {
        loadMoreButton.disabled = true;
        loadMoreButton.textContent = '加载中...';
    }

    try {
        const url = currentKeyword
            ? `/api/products?keyword=${encodeURIComponent(currentKeyword)}`
            : `/api/products?start=${currentPage * 10}&count=10`;

        const response = await fetch(url);
        const products = await response.json();

        if (response.ok) {
            if (products.length === 0) {
                hasMore = false;
                if (currentPage === 0) {
                    document.querySelector('.products-grid').innerHTML = `
                        <div class="no-products">暂无商品</div>
                    `;
                }
            } else {
                const productsGrid = document.querySelector('.products-grid');
                products.forEach(product => {
                    productsGrid.appendChild(createProductCard(product));
                });
                currentPage++;
            }
        } else {
            showMessage('products-message', products.error || '加载商品失败', true);
        }
    } catch (error) {
        console.error('加载商品失败:', error);
        showMessage('products-message', '加载商品失败，请重试', true);
    } finally {
        isLoading = false;
        if (loadMoreButton) {
            loadMoreButton.disabled = false;
            loadMoreButton.textContent = hasMore ? '加载更多' : '没有更多了';
        }
    }
}

// 创建商品卡片
function createProductCard(product) {
    const card = document.createElement('div');
    card.className = 'product-card';
    card.onclick = () => window.location.href = `/product.html?id=${product.id}`;

    card.innerHTML = `
        <img src="${product.images[0] || '/images/placeholder.jpg'}" alt="${product.name}" class="product-image">
        <div class="p-4">
            <h3 class="product-name">${product.name}</h3>
            <p class="product-description">${product.description}</p>
            <div class="product-price">¥${product.price.toFixed(2)}</div>
        </div>
    `;

    return card;
}

function upgrade_search_history() {
    const smBreakpoint = 640; // Tailwind 的 sm 断点
    if (window.innerWidth <= smBreakpoint) {
        const searchHistoryContainer = document.getElementById('sm-search-history-list');
        searchHistoryContainer.innerHTML = ''; // 清空历史记录

        for (let i = searchHistory.length - 1; i >= 0; i--) {
            const keyword = searchHistory[i];
            // 创建搜索历史项
            const span = document.createElement('span');
            span.className = 'block px-4 py-2 bg-gray-200 cursor-pointer rounded-lg text-black';
            span.textContent = keyword;
            span.onclick = () => {
                currentKeyword = keyword;
                document.getElementById('sm-normal-search').value = keyword;
            };
            searchHistoryContainer.appendChild(span);
        }

    }
    else {
        const searchHistoryContainer = document.getElementById('search-history-list');
        searchHistoryContainer.innerHTML = ''; // 清空历史记录

        for (let i = searchHistory.length - 1; i >= 0; i--) {
            const keyword = searchHistory[i];
            // 创建搜索历史项
            const div = document.createElement('div');
            div.className = 'px-4 py-2 hover:bg-gray-100 history';
            div.textContent = keyword;
            div.onclick = () => {
                currentKeyword = keyword;
                document.getElementById('normal-search').value = keyword;
                document.getElementById("search-history").style.display = "none";
            };
            searchHistoryContainer.appendChild(div);
        }

    }
}

// 搜索商品
function searchProducts() {
    const smBreakpoint = 640; // Tailwind 的 sm 断点
    let keyword;
    if (window.innerWidth <= smBreakpoint) {
        keyword = document.getElementById('sm-normal-search').value.trim();
    } else {
        keyword = document.getElementById('normal-search').value.trim();
        document.getElementById("search-history").style.display = "none";
    }

    if( keyword === '') {
        currentKeyword = '';
        loadProducts(true);
    }

    if (keyword !== currentKeyword && keyword !== '') {
        currentKeyword = keyword;
        searchHistory.push(keyword);
        if (searchHistory.length > 3) {
            searchHistory.shift(); // 保持最多 3 个搜索历史
        }
        // 去重
        searchHistory = [...new Set(searchHistory)];
        loadProducts(true);
        upgrade_search_history();
    }

}

// 监听搜索输入
document.getElementById('normal-search').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
        searchProducts();
    }
});
document.getElementById('sm-normal-search').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
        searchProducts();
    }
});

// 监听滚动加载
window.addEventListener('scroll', () => {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 500) {
        loadProducts();
    }
});

// 页面加载完成后加载商品
document.addEventListener('DOMContentLoaded', () => {
    // 从URL获取搜索关键词
    const urlKeyword = new URL(window.location.href).searchParams.get("search");
    if (urlKeyword) {
        document.getElementById('normal-search').value = urlKeyword;
        document.getElementById('sm-normal-search').value = urlKeyword;
        searchProducts();
    } else {
        document.getElementById('normal-search').value = '';
        document.getElementById('sm-normal-search').value = '';
        loadProducts();
    }
}); 